from app.model.user_model import UserModel
from app.model.store_model import StoreModel
from app.controller.validate.store_validate import StorePostValidate, StoreStatusPutValidate
from app.constant import StoreStatus
from .shoutcut_import import *
from app.model.image_model import ImageModel

bp = V1BluePoint('store', __name__, url_prefix='')


@bp.route('store', methods=['POST'])
@any_user_require
@validate_form(StorePostValidate)
def post_store():
    """用户申请店主接口
    1. 获取申请的信息
    2. 保存到数据库
    3. 更新user表的store_id
    """
    uid = g.uid
    user = UserModel.query.filter_by(id=uid).first()
    if not user:
        return error_json(ResponseCode.RESOURCE_NOT_FOUND, '用户异常')

    if user.store_id:
        return error_json(ResponseCode.OPERATOR_ERROR, '你已经是店主或已经在审核中！')

    ids = [request.json.get('img_shopkeeper_id_card_id'),
           request.json.get('img_logo_id'),
           request.json.get('img_business_license_id')]
    # 检查图片id是否存在数据库里
    if not ImageModel.check_image(ids):
        return error_json(ResponseCode.PARAMETER_ERROR, '存在图片id不存在')

    store = StoreModel(request.json, uid, StoreStatus.IN_AUDIT)
    sqla_db.session.add(store)
    sqla_db.session.commit()
    if not store.id:
        return error_json(ResponseCode.INTERNAL_SERVER_ERROR, '保存信息失败')
    user.store_id = store.id
    sqla_db.session.commit()
    return success_json()


@bp.route('store/status', methods=['PUT'])
@any_user_require  # 要改为admin
@validate_form(StoreStatusPutValidate)
def put_store_status():
    """管理员审核用户店铺接口
    1. 获取申请的商铺id
    2. 更改商铺的状态
    """
    store_id = request.json.get('store_id')
    status = request.json.get('status')
    store = StoreModel.query.filter_by(id=store_id).first()
    if not store:
        return error_json(ResponseCode.RESOURCE_NOT_FOUND, '商铺无法找到')

    store.update_status(status)
    sqla_db.session.commit()
    return success_json()